﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;

using NCT.Framework;
using NCT.Framework.Database;

using VISS.API.Commons;

namespace VISS.API.Users {
    class UserPropertyBC : IUserProperty {

        #region IUserProperty Members

        public EUserPropertySendPropertyResult SendProperty(string senderUserKey, string receiverUserKey, PropertyEnt propertyItem, string message) {
            EUserPropertySendPropertyResult result = EUserPropertySendPropertyResult.Success;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {
                 //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                UserPointBalanceEnt pointBalanceItem = new UserPointBalanceEnt() {
                    UserKey = senderUserKey,
                    RefUserKey = receiverUserKey,
                    Action = EUsePointBalanceActionType.BuyProperty,
                    PointUsed = propertyItem.PointPrice,
                    CoinUsed = propertyItem.CoinPrice,
                    DateCreated = DateTime.Now
                };

                if (pointBalanceItem.PointUsed > 0) {
                    UserGeneralProfileEnt generalProfileItem = UserGeneralProfileDA.GetByUserKey(senderUserKey, connectionName, null, null);
                    if (generalProfileItem == null) {
                        return EUserPropertySendPropertyResult.SystemError;
                    }
                    if (generalProfileItem.LeftPoint < propertyItem.PointPrice) {
                        return EUserPropertySendPropertyResult.NotEnoughPoint;
                    }

                    int leftPoint = 0;
                    if (UserGeneralProfileDA.DecreaseLeftPoint(senderUserKey, propertyItem.PointPrice, out leftPoint, connectionName, dbCon, dbTrans) <= 0) {
                        return EUserPropertySendPropertyResult.SystemError;
                    }
                }

                //Connect to NCT Coin Server to get sender user coin archive
                if (pointBalanceItem.CoinUsed > 0) {
                }

                if (UserPointBalanceDA.Insert(pointBalanceItem, connectionName, dbCon, dbTrans) <= 0) {
                    return EUserPropertySendPropertyResult.SystemError;
                }

                UserPropertyEnt item = new UserPropertyEnt() {
                    GiverUserKey = senderUserKey,
                    ReceiverUserKey = receiverUserKey,
                    PropertyID = propertyItem.ID,
                    Status = EUserPropertyStatus.NotAccepted,
                    Message = message,
                    DateCreated = DateTime.Now
                };

                if (UserPropertyDA.Insert(item, connectionName, dbCon, dbTrans) <= 0) {
                    return EUserPropertySendPropertyResult.SystemError;
                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserPropertyBC.SendProperty({0}, {1}, {2}): \n" + ex.ToString(),
                                    senderUserKey, receiverUserKey, SerializerUtils.JsonSerialize(propertyItem)));
                return EUserPropertySendPropertyResult.SystemError;
            }
            finally {
                if (dbTrans != null) {
                    if (result == EUserPropertySendPropertyResult.Success) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();

                }
            }
            return result;
        }

        public bool SendProperty(UserPropertyEnt item) {
            bool result = true;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {

                if (item.DateCreated == DateTimeUtils.MinValue) {
                    item.DateCreated = DateTime.Now;
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                //Create connection & transaction
                dbCon = Database.CreateConnection(connectionName, true);
                dbTrans = dbCon.BeginTransaction();

                // Insert UserImage to DB
                result = UserPropertyDA.Insert(item, connectionName, dbCon, dbTrans) > 0;
            }
            catch (Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserPropertyBC.Insert({0}): \n" + ex.ToString(),
                                    SerializerUtils.JsonSerialize(item)));
                result = false;
            }
            finally {
                if (dbTrans != null) {
                    if (result) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();

                }
            }
            return result;
        }

        public bool AcceptProperty(long iD, string userKey) {
            return UpdateStatus(new UserPropertyEnt() { ID = iD, ReceiverUserKey = userKey, Status = EUserPropertyStatus.Accepted }); ;
        } 

        public bool DenyProperty(long iD, string userKey) {
            return UpdateStatus(new UserPropertyEnt() { ID = iD, ReceiverUserKey = userKey, Status = EUserPropertyStatus.Delete }); ;
        }

        public bool DeleteProperty(long iD, string userKey) {
            return UpdateStatus(new UserPropertyEnt() { ID = iD, ReceiverUserKey = userKey, Status = EUserPropertyStatus.Delete }); ;
        }

        public bool UpdateStatus(long iD, string userKey, EUserPropertyStatus status) {
            return UpdateStatus(new UserPropertyEnt() { ID = iD, ReceiverUserKey = userKey, Status = status });
        }

        public bool UpdateStatus(UserPropertyEnt item) {
            bool result = true;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                //Create connection & transaction
                dbCon = Database.CreateConnection(connectionName, true);
                dbTrans = dbCon.BeginTransaction();

                // Insert UserImage to DB
                result = UserPropertyDA.UpdateStatus(item, connectionName, dbCon, dbTrans) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserPropertyBC.UpdateStatus({0}): \n" + ex.ToString(),
                                                    SerializerUtils.JsonSerialize(item)));
                result = false;
            }
            finally {
                if (dbTrans != null) {
                    if (result) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();

                }
            }
            return result;
        }

        public int CountNotAcceptedProperty(string userKey) {
            return CountByReceiverUserKeyStatus(userKey, EUserPropertyStatus.NotAccepted);
        }

        public int CountAcceptedProperty(string userKey) {
            return CountByReceiverUserKeyStatus(userKey, EUserPropertyStatus.Accepted);
        }

        public int CountByReceiverUserKeyStatus(string receiverUserKey, EUserPropertyStatus status) {
            int result = 0;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                result = UserPropertyDA.CountByReceiverUserKeyStatus(receiverUserKey, status, connectionName);
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserPropertyBC.CountByReceiverUserKeyStatus({0}, {1}): \n" + ex.ToString(),
                                    receiverUserKey, status));
                result = 0;
            }
            return result;
        }

        public List<UserPropertyEnt> GetNotAcceptedPropertyWithPaging(string userKey, int page, int recordPerPage, out int totalRecord) {
            return GetByReceiverUserKeyStatusWithPaging(userKey, EUserPropertyStatus.NotAccepted, page, recordPerPage, out totalRecord);
        }

        public List<UserPropertyEnt> GetAcceptedPropertyWithPaging(string userKey, int page, int recordPerPage, out int totalRecord) {
            return GetByReceiverUserKeyStatusWithPaging(userKey, EUserPropertyStatus.Accepted, page, recordPerPage, out totalRecord);
        }

        public List<UserPropertyEnt> GetByReceiverUserKeyStatusWithPaging(string receiverUserKey, EUserPropertyStatus status, int page, int recordPerPage, out int totalRecord) {
            List<UserPropertyEnt> result = new List<UserPropertyEnt>();
            totalRecord = 0;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                totalRecord = UserPropertyDA.CountByReceiverUserKeyStatus(receiverUserKey, status, connectionName);
                if (totalRecord == 0) {
                    return result;
                }

                int totalPage = (int)(totalRecord / recordPerPage);
                if (totalRecord % recordPerPage != 0) {
                    totalPage++;
                }
                if (page > totalPage) {
                    return result;
                }

                long startRow = (page - 1) * recordPerPage + 1;
                long endRow = startRow + recordPerPage - 1;

                if (endRow > totalRecord) {
                    endRow = totalRecord;
                }

                result = UserPropertyDA.GetByReceiverUserKeyStatusWithPaging(receiverUserKey, status, startRow, endRow, connectionName, null, null);
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserPropertyBC.CountByReceiverUserKeyStatus({0}, {1}, {2}, {3}): \n" + ex.ToString(),
                                    receiverUserKey, status, page, recordPerPage));
                result = new List<UserPropertyEnt>();
            }
            return result;
        }

        #endregion
    }
}
